module.exports={
	/*
	 * 单一数组转根据ID和PID转日录树
	 * 用法，listToTree(array,{
	 * 	"idKey":"id",//id
	 * 	"parentKey":"parent",//父ID
	 * 	"children":"children"//子ID名
	 * });
	 * @date 数据组
	 * @options 格式化方法 传入 ID PID 和子目录名
	 */
	listToTree:function (data, {idKey='id',parentKey="pid",childrenKey='children'}={}) {
		let tree = [],childrenOf = {},length = data.length;
		let item,id,parentId;
		for (let i = 0; i < length; i++) {
			item = data[i];
			id = item[idKey];
			parentId = item[parentKey] || 0;
			// every item may have children
			childrenOf[id] = childrenOf[id] || [];
			// init its children
			item[childrenKey] = childrenOf[id];
			if (parentId != 0) {
			// init its parent's children object
			childrenOf[parentId] = childrenOf[parentId] || [];
			// push it into its parent's children object
			childrenOf[parentId].push(item);
			} else {
				tree.push(item);
			}
		}
		return tree;
	},
	/*
	 * 树结构转成数组结构
	 * treeToList(array,{
	 * 	"idKey":"id",//id
	 * 	"parentKey":"parent",//父ID
	 * 	"children":"children"//子ID名
	 * });
	 * @date 数据组
	 * @options 格式化方法 传入 ID PID 和子目录名
	 */
	treeToList:function (data, {idKey='id',parentKey="pid",childrenKey='children'}={}) {
		if(data.length<1){
			return;
		}else{
			let arr=[],store=0;
			function appenChildren(tree,treepid=0,){
				let l=tree.length;
				let item;
				for (let i=0; i <l; i++){
					item=tree[i];
					item.store=store;
					store++;
					item[parentKey]=treepid;
					arr.push(item);
					if (item[childrenKey].length>0) {
						appenChildren(item[childrenKey],item[idKey],store);
					}
				}
			}
			appenChildren(data);
			return arr;
		}
		
	},
  	/*
	 * @name 图片预览
	 * @param file  file 文件对像
	 * @param Number  maxLen 处理单位为PX
	 * @param function   callBack 回调函数 返回 文件base64值
  	 */
  	imgToBase64: function async (file, maxLen=300,callBack) {
        let img = new Image();
        let reader = new FileReader();
        reader.onload = function () {
          	img.src = reader.result;
        }
        img.onload = function () {
			let width = img.width, height = img.height;
			let rate = 1;
			let maxImgLen=(width>height)?width:height;
			if(maxImgLen > maxLen ){
				rate = maxLen / maxImgLen;
			}
			img.width = width * rate;
			img.height = height * rate;
			let canvas = document.createElement("canvas");
			let ctx = canvas.getContext("2d");
			canvas.width = img.width;
			canvas.height = img.height;
			ctx.drawImage(img, 0, 0, img.width, img.height);
			let base64 = canvas.toDataURL('image/jpeg', 1);
			callBack(base64);
        }
		reader.readAsDataURL(file);
  	},
}